/**
 * Created by Noir on 1/10/14.
 */
'use strict'

angular.module('2order.system')
    .directive('toFollow',['$http', ToFollowDirective]);

function ToFollowDirective($http){
    return {
        restrict: 'EA',
        templateUrl: '/views/component/followButton.html',
        scope:{
        },
        controller:function($scope){
            $scope.isLoading = true;

            $scope.button = {}
            $scope.communicate = function(){
                if($scope.status=='followed'){
                    // then un-friend
                    unfollow();
                }else if($scope.status == 'unfollow'){
                    // then cancel request
                    follow();
                }
            }

            this.updateFollowStatus = updateFollowStatus;

            function updateFollowStatus(data){
                $scope.status = data;
                if(data=='followed'){
                    $scope.button.name = 'unfollow';
                    $scope.button.class = 'btn-danger';
                    $scope.button.label = 'Unfollow';
                }else if(data == 'unfollow'){
                    $scope.button.name = 'follow';
                    $scope.button.class = 'btn-primary';
                    $scope.button.label = 'Follow';
                }

                // hide loading button
                $scope.isLoading = false;
            }

            function follow(){
                // show loading button
                $scope.isLoading = true;
                // call add friend now
                $http({
                    method:'PUT',
                    url:'/api/follow',
                    data: $.param({id: $scope.$parent.owner._id }),
                    headers:{'Content-Type':'application/x-www-form-urlencoded'}
                })
                    .success(function(data, status){
                        updateFollowStatus('followed');
                    });
            }

            function unfollow(){
                // show loading button
                $scope.isLoading = true;
                // call add friend now
                $http({
                    method:'PUT',
                    url:'/api/unfollow',
                    data: $.param({id: $scope.$parent.owner._id }),
                    headers:{'Content-Type':'application/x-www-form-urlencoded'}
                })
                    .success(function(data, status){
                        updateFollowStatus('unfollow');
                    });
            }
        },
        link: function(scope, ele, attrs, ctrl){
            ctrl.updateFollowStatus(attrs.status);
        }
    }
};


